{% extends "base.html" %}

{% block content %}
<h1>Payee list</h1>

<p class="description">TODO</p>

<button class="create-payee">Create new payee</button>

<div class="list payee-list">
	<h2>Payees</h2>
	{% if payees %}
		<table class="table-list" cellpadding="0" cellspacing="0">
			<thead>
				<tr class="header">
					<th class="first string payee-title">Payee</th>
					<th class="string payee-author">Author</th>
					<th class="datetime payee-createdat">Created At</th>
					<th class="last datetime payee-updatedat">Updated At</th>
				</tr>
			</thead>
			<tbody id="payee-list-tbbody">
				{% include 'payee_list_tmpl.html' %}
			</tbody>
		</table>
	{% endif %}
</div>

<button class="create-payee">Create new payee</button>

<div id="dialog-form" title="Create/Edit a payee">
	{% include 'payee_submit.html' %}
</div>

<script>
	$(function() {
		$("#dialog-form").dialog({
			autoOpen: false,
			height: 120,
			width: 250,
			modal: true,
			resizable: false,
			buttons: {
				"Submit": function() {
					var popup = $(this);
					$.ajax({
					  type: 'POST',
					  url: '/payee/submit',
					  data: { title: $('#payee-title').val() },
					  success: function(data, textStatus, jqXHR) {
						  if(data) {
							  if(data.result == 'SUCCESS') {
								  $('#payee-list-tbbody').html(data.html);
								  
								  popup.dialog("close");
								  
								  $('#payee_' + data.id).effect("highlight", {}, 4000);
							  }
							  else if(data.result == 'FAILED') {
								  $('.payee-error').hide();
							  		
								  $.each(data.errors, function(key, value) {
									  $('#payee-' + key + '-error').html(value);
									  $('#payee-' + key + '-error').show();
								  });
							  }
						  }
						  else {
							  this.error();
						  }
					  },
					  error: function() { 
						  alert("An error occurred. Please retry or contact the administrator.");
					  },
					  dataType: 'json'
					});
				},
				Cancel: function() {
					$(this).dialog("close");
				}
			},
			close: function() {
				//allFields.val("").removeClass( "ui-state-error" );
			}
		});
		
		$(".create-payee").button().click(function() {
			$("#dialog-form").dialog("open");
		});
	});
	
	function edit(key) {
		$.ajax({
			  type: 'POST',
			  url: '/payee/get',
			  data: { key: key },
			  success: function(data, textStatus, jqXHR) {
				  if(data && data.result == 'SUCCESS') {
					  $("#dialog-form").dialog("open");
					  
					  $('#payee-title').val(data.payee)
				  }
				  else {
					  this.error();
				  }
			  },
			  error: function() { 
				  alert("An error occurred. Please retry or contact the administrator.");
			  },
			  dataType: 'json'
			});
	}
</script>

{% endblock %}
